/*
 * @Author: lyuan2018
 * @Date: 2019-08-13 14:07:32
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-08-20 16:55:37
 * page: 联系人页面
 */
import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import {
  WeaTop,
  WeaLocaleProvider,
  WeaInputSearch,
  WeaCheckbox,
  WeaNewScrollPagination,
  WeaAlertPage,
  WeaMoreButton,
  WeaRightMenu,
} from 'ecCom';
import { Tooltip, Spin, Card, Button, Modal } from 'antd';
import EmailGroup from './emailContacts/Group';
import AddContact from './emailContacts/AddContact';
import PopoverAccount from './com/PopoverAccount';
import PopoverMove from './emailContacts/PopoverMove';
import ContactTop from './emailContacts/ContactTop';

const getLabel = WeaLocaleProvider.getLabel;

@inject('routing', 'emailContactStore')
@observer
class EmailContact extends Component {
  static defaultProps = {
    prefixCls: 'email-contact',
  };

  constructor(props) {
    super(props);
    this.state = {
      addContVisible: false,
      moveVisible: false,
      copyVisible: false,
      searchValue: '',
    };
  }

  componentWillReceiveProps(nextProps) {
    const { emailContactStore } = this.props;
    const {
      location: { pathname, key },
    } = this.props;
    const {
      location: {
        pathname: _pathname,
        key: _key,
        query: { ontabchange },
      },
    } = nextProps;
    if (
      (pathname !== _pathname || key !== _key) &&
      !ontabchange &&
      _pathname.indexOf('main/email/contacts') > -1
    ) {
      this.setState({
        addContVisible: false,
        moveVisible: false,
        copyVisible: false,
        searchValue: '',
      });
      emailContactStore.clear();
      emailContactStore.getContactCountList();
      emailContactStore.getContactList();
    }
  }

  componentWillMount() {
    const { emailContactStore } = this.props;
    emailContactStore.getContactCountList();
    emailContactStore.getContactList();
  }

  componentWillUnmount() {
    const { emailContactStore } = this.props;
    emailContactStore.clear();
  }

  // 内容部分
  renderContacts = (datas) => {
    const {
      prefixCls,
      emailContactStore: { usergroups, groupSubmit, changeContactSelect },
    } = this.props;
    if (datas && datas.length > 0) {
      return (
        <div className={`${prefixCls}-container-users-main`}>
          {datas.map((data) => {
            const {
              id,
              mailUserName,
              mailaddress,
              groups,
              contactChecked,
              mailUserMobileP,
            } = data;
            const groupsName = groups.map(v => v.groupName).join();
            const popoverData = this.setPopoverData(data);
            return (
              <Card
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_Card@x0inp4@${id}`}
                key={id}
                className="user-item"
              >
                <div className="checkbox">
                  <WeaCheckbox
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_WeaCheckbox@13lhpe@${id}`}
                    value={contactChecked}
                    onChange={v => changeContactSelect(v, data)}
                  />
                </div>
                <PopoverAccount
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_PopoverAccount@v38yad@${id}`}
                  onOperateClick={this.contentClick}
                  data={popoverData}
                >
                  <div className="content">
                    <p>
                      <Tooltip
                        ecId={`${
                          (this && this.props && this.props.ecId) || ''
                        }_Tooltip@zckmyy@${id}`}
                        placement="bottom"
                        title={mailUserName || ''}
                      >
                        <span>{mailUserName || ''}</span>
                      </Tooltip>
                    </p>
                    <p>
                      <Tooltip
                        ecId={`${
                          (this && this.props && this.props.ecId) || ''
                        }_Tooltip@9pvr77@${id}`}
                        placement="bottom"
                        title={
                          (
                            <span style={{ wordBreak: 'break-all' }}>
                              {mailaddress}
                            </span>
                          ) || ''
                        }
                      >
                        <span>{mailaddress || ''}</span>
                      </Tooltip>
                    </p>
                    <p>
                      <Tooltip
                        ecId={`${
                          (this && this.props && this.props.ecId) || ''
                        }_Tooltip@a8ms1g@${id}`}
                        placement="bottom"
                        title={mailUserMobileP || ''}
                      >
                        <span>{mailUserMobileP || ''}</span>
                      </Tooltip>
                    </p>
                  </div>
                </PopoverAccount>
                <div className="group">
                  <EmailGroup
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_EmailGroup@nsp1xq@${id}`}
                    wrapCls={`${prefixCls}-container-users-group`}
                    groups={toJS(usergroups)}
                    concactIds={id}
                    inGroup={groups}
                    onSubmit={groupSubmit} // 保存提交事件
                    newGroup={this.newGroup} // 新建分组事件
                  >
                    {this.renderGroupTitle(groups, groupsName)}
                  </EmailGroup>
                </div>
              </Card>
            );
          })}
        </div>
      );
    }
    return (
      <WeaAlertPage
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaAlertPage@mqd2s0`}
        icon="icon-coms-blank"
      >
        <div style={{ color: '#000' }}>
          {getLabel(83320, '没有可显示的数据')}
        </div>
      </WeaAlertPage>
    );
  };

  setPopoverData = (data) => {
    let obj = {};
    for (let key in data) {
      if (key == 'mailaddress') obj.email = data[key];
      if (key == 'mailUserName') obj.showName = data[key];
    }
    obj.isInternal = 0;
    obj.canEdit = true;
    obj.key = data.id;
    return obj;
  };

  // 内容点击
  contentClick = (key, item) => {
    const {
      emailContactStore: { contactCondition, setStoreState },
    } = this.props;
    const { showName, email } = item.data;
    const editId = item.data.key;
    if (key === 'editContact') {
      let params = { id: editId, mailUserName: showName, mailAddress: email };
      contactCondition(params);
      setStoreState({ editId, addContactTitle: getLabel(31229, '编辑联系人') });
      this.setState({ addContVisible: true });
    }
  };

  renderGroupTitle = (groups, groupsName) => (
    <div className="user-group">
      {groups.length === 0 ? (
        <Tooltip
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Tooltip@6g7bzb`}
          title={getLabel(81307, '未分组')}
          placement="bottom"
        >
          <span>{getLabel(81307, '未分组')}</span>
        </Tooltip>
      ) : (
        <Tooltip
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Tooltip@a6leep`}
          title={groupsName}
          placement="bottom"
          overlayStyle={{
            maxWidth: 185,
            wordWrap: 'break-word',
            wordBreak: 'break-all',
          }}
        >
          <span>{groupsName}</span>
        </Tooltip>
      )}
      <span className="icon-coms-organization-down" />
    </div>
  );

  newGroup = (params, callback) => {
    const { emailContactStore } = this.props;
    const { newGroup } = emailContactStore;
    newGroup(params, callback);
  };

  // 批量写信
  write = () => {
    const {
      routing,
      emailContactStore: { contactSelect },
    } = this.props;
    let str = '';
    toJS(contactSelect) &&
      toJS(contactSelect).forEach((o, l) => {
        str += o.mailaddress;
        if (l !== toJS(contactSelect).length - 1) str += ',';
      });
    routing.push({
      pathname: 'main/email/new',
      query: {
        isInternal: 0,
        to: str,
      },
    });
  };

  // 从改组移除
  removeFromGroup = () => {
    const {
      emailContactStore: { curgroupId, moveCopyGroup, contactSelect },
    } = this.props;
    let concactIds = toJS(contactSelect)
      .map(v => v.id)
      .join();
    let params = {
      operation: 'deleteContactFromGourp',
      concactIds,
      sourceGroup: curgroupId,
    };
    moveCopyGroup(params);
  };

  // 删除联系人
  deleteContact = () => {
    const {
      emailContactStore: { moveCopyGroup, contactSelect },
    } = this.props;
    Modal.confirm({
      content: `${getLabel('506446', '确定删除联系人')}?`,
      okText: getLabel(826, '确定'),
      cancelText: getLabel(31129, '取消'),
      onOk: () => {
        let concactIds = toJS(contactSelect)
          .map(v => v.id)
          .join();
        let params = { operation: 'deleteContact', concactIds };
        moveCopyGroup(params);
      },
    });
  };

  getMoreButton = () => {
    const {
      emailContactStore: { contactSelect, curgroupId },
    } = this.props;
    let moreButton = [
      {
        key: 'addContacts',
        content: getLabel(19956, '添加联系人'),
        disabled: false,
        onClick: () => {
          this.refs.addContact &&
            this.refs.addContact.wrappedInstance.addContacts();
        },
      },
      {
        key: 'write',
        content: getLabel(81300, '写信'),
        disabled: true,
        onClick: this.write,
      },
      {
        key: 'remove',
        content: getLabel(384341, '从该组移除'),
        disabled: true,
        onClick: this.removeFromGroup,
      },
      {
        key: 'delete',
        content: getLabel(91, '删除'),
        disabled: true,
        onClick: this.deleteContact,
      },
      {
        key: 'export',
        content: getLabel(28343, '导出Excel'),
        disabled: true,
        onClick: this.export,
      },
    ];
    if (toJS(contactSelect).length !== 0) {
      moreButton.forEach((item) => {
        item.disabled = false;
        if (item.key == 'remove' && (curgroupId == 0 || curgroupId == '-1')) {
          item.disabled = true;
        }
      });
    }
    return moreButton;
  };

  export = () => {};

  // 右键菜单
  getRightMenu() {
    let btns = [];
    btns.push({
      key: 'search',
      icon: <i className="icon-coms-search" />,
      content: getLabel(197, '搜索'),
    });
    return btns;
  }

  // 右键菜单事件绑定
  onRightMenuClick = (key) => {
    const { emailContactStore } = this.props;
    const { getContactList } = emailContactStore;
    if (key == 'search') {
      getContactList({ keyword: this.state.searchValue });
    }
  };

  onHandleAdd = () => this.setState({ addContVisible: true });
  onHandleCancel = () => this.setState({ addContVisible: false });
  onHandleSubmit = (data, isEdit) => {
    const { emailContactStore } = this.props;
    const {
      getContactList,
      curgroupId,
      getContactCountList,
      updateContactList,
    } = emailContactStore;
    if (isEdit) {
      // 编辑
      let res = data.datas && data.datas[0];
      updateContactList(res.id, res);
    } else {
      getContactList();
    }
    getContactCountList({ groupId: curgroupId });
  };

  render() {
    const { prefixCls, emailContactStore } = this.props;
    const {
      contentLoading,
      usercontent,
      onScrollEnd,
      getContactList,
      contactSelect,
      changeAllContactSelect,
      curgroupId,
    } = emailContactStore;
    const buttons = [
      <WeaInputSearch
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaInputSearch@tiybsk@contacts`}
        placeholder={getLabel(384346, '姓名、邮件、手机')}
        onSearch={value => getContactList({ keyword: value })}
        onSearchChange={value => this.setState({ searchValue: value })}
        value={this.state.searchValue}
      />,
    ];
    const optButtons = [
      // 底部操作按钮
      {
        key: 'addContacts',
        name: getLabel(19956, '添加联系人'),
        disabled: false,
        operation: () => {
          this.refs.addContact &&
            this.refs.addContact.wrappedInstance.addContacts();
        },
        shouldPopover: false,
        text: '',
      },
      {
        key: 'write',
        name: getLabel(81300, '写信'),
        disabled: true,
        operation: this.write,
        shouldPopover: false,
        text: '',
      },
      {
        key: 'move',
        name: getLabel(81298, '移动到'),
        disabled: true,
        operation: () => {},
        shouldPopover: true,
        text: getLabel(31194, '新建分组并移动'),
      },
      {
        key: 'copy',
        name: getLabel(383953, '复制到'),
        disabled: true,
        operation: () => {},
        shouldPopover: true,
        text: getLabel(31195, '新建分组并复制'),
      },
      {
        key: 'remove',
        name: getLabel(384341, '从该组移除'),
        disabled: true,
        operation: this.removeFromGroup,
        shouldPopover: false,
        text: '',
      },
      {
        key: 'delete',
        name: getLabel(91, '删除'),
        disabled: true,
        operation: this.deleteContact,
        shouldPopover: false,
        text: '',
      },
    ];
    return (
      <WeaRightMenu
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaRightMenu@7lfaj2`}
        datas={this.getRightMenu()}
        onClick={this.onRightMenuClick}
      >
        <div className={prefixCls}>
          <WeaTop
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaTop@95ehx2`}
            title={
              <ContactTop
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_ContactTop@qigfwv`}
                wrapCls={prefixCls}
              />
            }
            buttons={buttons}
            loading={contentLoading}
          />
          <div className={`${prefixCls}-container`}>
            <div className={`${prefixCls}-container-check`}>
              <WeaCheckbox
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaCheckbox@gw666x`}
                content={getLabel(556, '全选')}
                value={
                  toJS(contactSelect).length === toJS(usercontent).length &&
                  toJS(contactSelect).length > 0
                }
                onChange={changeAllContactSelect}
              />
              <span className="element">
                {getLabel(31503, '已选择')}
                <span>{toJS(contactSelect).length}</span>
                {getLabel(384340, '个对象')}
              </span>
            </div>
            <div className={`${prefixCls}-container-users`}>
              <WeaNewScrollPagination
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaNewScrollPagination@cd56r5`}
                height={'100%'}
                onScrollEnd={onScrollEnd}
              >
                <Spin
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_Spin@kwgixg`}
                  spinning={contentLoading}
                >
                  {this.renderContacts(toJS(usercontent))}
                </Spin>
              </WeaNewScrollPagination>
            </div>
            <div className={`${prefixCls}-container-ops`}>
              {optButtons.map((item) => {
                let disabled = false;
                if (item.disabled) disabled = toJS(contactSelect).length === 0;
                if (
                  item.key == 'remove' &&
                  (curgroupId == 0 || curgroupId == '-1')
                ) {
                  // 从该组移除：选中组后可用
                  disabled = true;
                }
                if (!item.shouldPopover) {
                  return (
                    <Button
                      ecId={`${
                        (this && this.props && this.props.ecId) || ''
                      }_Button@gws8pv@${item.key}`}
                      className="opt-btn"
                      key={item.key}
                      type="primary"
                      onClick={item.operation}
                      disabled={disabled}
                    >
                      {item.name}
                    </Button>
                  );
                }
                return (
                  <PopoverMove
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_PopoverMove@o1zgo2@${item.key}`}
                    datas={item}
                    key={item.key}
                    wrapCls="opt-btn"
                    visible={this.state[`${item.key}Visible`]}
                    onCancel={() => {
                      this.setState({ [`${item.key}Visible`]: false });
                    }}
                  >
                    <Button
                      ecId={`${
                        (this && this.props && this.props.ecId) || ''
                      }_Button@9ncl59@${item.key}`}
                      type="primary"
                      disabled={disabled}
                      onClick={() =>
                        this.setState({
                          [`${item.key}Visible`]: !this.state[
                            [`${item.key}Visible`]
                          ],
                        })
                      }
                    >
                      {item.name}
                    </Button>
                  </PopoverMove>
                );
              })}
              <WeaMoreButton
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaMoreButton@3ybyjw`}
                datas={this.getMoreButton()}
                collectParams={{
                  favname: getLabel(572, '联系人'),
                  favouritetype: 2,
                  objid: 0,
                  importantlevel: 1,
                }}
              />
            </div>
          </div>
          <AddContact
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_AddContact@3lwrn9`}
            ref="addContact"
            visible={this.state.addContVisible}
            onHandleAdd={this.onHandleAdd}
            onCancel={this.onHandleCancel}
            onSubmit={this.onHandleSubmit}
          />
        </div>
      </WeaRightMenu>
    );
  }
}

export default EmailContact;
